package com.yaodian100.mall.member.web;

import java.io.IOException;
import java.net.URLEncoder;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.lang.StringUtils;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.yaodian100.core.admin.entity.User;
import com.yaodian100.core.common.utils.ServerValue;
import com.yaodian100.core.menu.service.MenuService;
import com.yaodian100.mall.member.util.UserData;

/**
 * 
 * @author apple.chang
 * 
 */
public class LoginFilter implements Filter {

	private MenuService menuService;

	public void destroy() {
		// TODO Auto-generated method stub

	}

	public void doFilter(ServletRequest request, ServletResponse response, FilterChain chain) throws IOException,
			ServletException {
		HttpServletRequest httpRequest = (HttpServletRequest) request;
		HttpServletResponse httpResponse = (HttpServletResponse) response;
		String uri = ServerValue.getFrontHostname() + httpRequest.getRequestURI();
		String queryStr = "";
		if (StringUtils.isNotBlank(httpRequest.getQueryString())) {
			queryStr += "?" + httpRequest.getQueryString();
		}
		try {
			String domainSrc = request.getServerName();
			UserData userData = new UserData(httpRequest, httpResponse);
			menuService = (MenuService) WebApplicationContextUtils.getRequiredWebApplicationContext(
					httpRequest.getSession().getServletContext()).getBean("menuService");
			String pclady = menuService.get("SystemValue").getOptions().get("pclady").getMemo1();
			if (domainSrc.equals(pclady)) {
				boolean isLogin = isLogin(userData, request);
				if (isLogin) {
					chain.doFilter(request, response);
				} else { // is not Login
					uri = "http://" + domainSrc + httpRequest.getRequestURI();
					String cobrandingLogin = "http://buy.pclady.com.cn/yaodianlogin.jsp?retUrl=";
					httpResponse.sendRedirect(cobrandingLogin + URLEncoder.encode(uri + queryStr, "utf-8"));
				}
			} else if (domainSrc.endsWith("yaodian100.com")) {
				boolean isLogin = isLogin(userData, request);
				if (isLogin) {
					User ecuser = new User(userData.getMemberId());
					// SecurityContextHolder.getContext().setAuthentication(
					// new UsernamePasswordAuthenticationToken(ecuser, "password"));
					chain.doFilter(request, response);
					// SecurityContextHolder.getContext().setAuthentication(null);
				} else { // is not Login
					httpResponse.sendRedirect(ServerValue.getFrontHostnameSsl() + ServerValue.getFrontContextPath()
							+ "/tologin.do?redirect_url=" + URLEncoder.encode(uri + queryStr, "utf-8"));
				}
			} else {
				boolean isLogin = isLogin(userData, request);
				if (isLogin) {
					User ecuser = new User(userData.getMemberId());
					// SecurityContextHolder.getContext().setAuthentication(
					// new UsernamePasswordAuthenticationToken(ecuser, "password"));
					chain.doFilter(request, response);
					// SecurityContextHolder.getContext().setAuthentication(null);
				} else { // is not Login
					uri = "http://" + domainSrc + httpRequest.getRequestURI();
					// String cobrandingLogin = "http://" + domainSrc + "/" + ServerValue.getFrontContextPath()
					// + "/cobranding/memberLogin.do?coBrand=" + domainSrc + "&sendTo=" + uri + queryStr;
					// httpResponse.sendRedirect("http://" + domainSrc + "/" + ServerValue.getFrontContextPath()
					// + "/tologin.do?redirect_url=" + URLEncoder.encode(cobrandingLogin, "utf-8"));
					httpResponse.sendRedirect("http://" + domainSrc + "/" + ServerValue.getFrontContextPath()
							+ "/tologin.do?redirect_url=" + URLEncoder.encode(uri + queryStr, "utf-8"));
				}

			}
		} catch (Exception e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
	}

	public void init(FilterConfig arg0) throws ServletException {
		// TODO Auto-generated method stub

	}

	private boolean isLogin(UserData userData, ServletRequest request) throws Exception {
		if (StringUtils.isNotBlank(userData.getLoginId())) {
			if (!request.getServerName().equals(userData.getLoginDamain())) {
				// 登入domain不同, 强制登出
				userData.clearAll();
				return false;
			}
			return true;
		}
		return false;
	}
}